package com.domain.oa.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.domain.oa.entity.User;
import com.domain.oa.mapper.UserMapper;
import com.domain.oa.service.UserService;
import com.domain.oa.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private UserService userService;

    @Resource
    private RedisUtils redisUtils;

    /**
     * 分页获取数据
     * @param pageNum
     * @param pageSize
     * @param userName
     * @return
     */
    @Transactional
    public ResultVo<User> getUserByPage(Integer pageNum, Integer pageSize, String userName) {
        QueryWrapper<User> query = new QueryWrapper<>();
        // 倒叙查询
        query.orderByDesc("id");
        // 排除被逻辑删除的值
        query.eq("is_delete", 0);
        // 判断是否有用户名，有的话模糊查询
        if(userName != "") {
            query.like("username", userName);
        }
        IPage<User> page = new Page<>(pageNum, pageSize);
        try {
            IPage<User> result = userMapper.selectPage(page, query);
            return new ResultVo(200, "分页获取成功！", result);
        }catch (Exception e) {
            return new ResultVo(405, "分页获取失败！", e);
        }
    }

    /**
     * 通过手机注册账号
     * @param phone
     * @param password
     * @return
     */
    @Transactional
    public ResultVo register(String phone, String password) {
        // 获取当前时间
        Date date = new Date();

        // 注册账号
        User user = new User();
        user.setPhone(phone);

        // 获取账号数量
        long count = userService.count();
        long l = count++;
        String countIndex = String.format("%0" + 3 + "d", l);

        // 添加一个随机账号
        String username = AccountUtils.generateAccount(countIndex);
        user.setUsername(username);

        // MD5加密密码
        String md5Password = MD5Util.string2MD5(password);
        user.setPassword(md5Password);

        // 设置创建时间
        user.setCreateTime(date);
        try {
            userService.save(user);
            return new ResultVo(200, "注册成功!", null);
        }catch (Exception e) {
            return new ResultVo(405, "注册失败!", e.getMessage());
        }
    }

    /**
     * 检查登录信息
     * @param phone
     * @param username
     * @param password
     * @return
     */
    @Transactional
    public ResultVo checkLogin(String phone, String username, String password) {
        try {
            QueryWrapper<User> query = new QueryWrapper<>();

            if(!phone.equals("")) {
                query.eq("phone", phone);
            }
            if(!username.equals("")) {
                query.eq("username", username);
            }
            // 查询数据
            User user = userService.getOne(query);

            // 初始化jwt信息
            HashMap<String, String> payload = new HashMap<>();
            payload.put("id", String.valueOf(user.getId()));
            payload.put("name", user.getUsername());

            // 生成TOKEN
            String token = JWTUtils.getToken(payload);

            // 用户输入的值加密
            String postPassword = MD5Util.string2MD5(password);

            // 设置存放在Redis中的用户信息
            user.setToken(token);
            String userInfo = "userInfo:" + user.getId();

            user.setToken(token);

            // 如果输入的是手机号或者账号正确
            if(phone.equals(user.getPhone()) || username.equals(user.getUsername())) {
                // 验证密码
                if(postPassword.equals(user.getPassword())) {
                    // 使用redis存储用户token信息
                    redisUtils.set(userInfo, user);
                    //返回用户能看到的封装好的信息
                    return new ResultVo(200, "登录成功!", user);
                }else {
                    return new ResultVo(402, "密码错误!", null);
                }
            }else {
                return new ResultVo(401, "账号或手机号错误!", null);
            }
        }catch (Exception e) {
            return new ResultVo(501, "系统错误,您的账号可能不存在!", e.getLocalizedMessage());
        }
    }

    /**
     * 根据角色id访问用户信息
     * @param userId
     * @return
     */
    @Override
    public ResultVo getUserInfoByUserId(Integer userId) {
        String redisKeyName = "userInfo:" + userId;
        User result = new User();
        try {
            result = (User) redisUtils.get(redisKeyName);
        }catch (Exception e){
            return new ResultVo(400, "系统错误！", e);
        }
        return new ResultVo(200, "根据角色id访问用户信息成功！", result);
    }

    /**
     * 添加用户
     * @param user
     * @return
     */
    @Override
    public ResultVo addUser(User user) {
        try {
            // 随机生成账号
            long count = userService.count();
            long l = count++;
            String countIndex = String.format("%0" + 3 + "d", l);
            String username = AccountUtils.generateAccount(countIndex);
            user.setUsername(username);

            Date date = new Date();
            user.setCreateTime(date);

            // 执行持久层的添加
            boolean integer = userService.save(user);
            if(integer) {
                return new ResultVo(200, "添加角色成功！", null);
            }else {
                return new ResultVo(201, "添加角色失败！", null);
            }
        }catch (Exception e) {
                return new ResultVo(501, "系统错误！", e.getMessage());
        }
    }

    /**
     * 编辑用户
     * @param user
     * @return
     */
    @Override
    public ResultVo editUser(User user) {
        try {
            user.setUpdateTime(new Date());
            boolean b = userService.saveOrUpdate(user);
            if (b) {
                return new ResultVo(200, "编辑用户成功!", null);
            }else {
                return new ResultVo(201, "编辑用户失败!", null);
            }
        }catch (Exception e) {
            return new ResultVo(505, "系统错误!", e.getLocalizedMessage());
        }
    }

    @Override
    public ResultVo pretendDelete(Integer userId) {
        try {
            boolean b = userMapper.pretendDelete(userId);
            if (b) {
                return new ResultVo(200, "删除用户成功!", null);
            }else {
                return new ResultVo(201, "删除用户失败!", null);
            }
        }catch (Exception e) {
            return new ResultVo(505, "系统错误!", e.getLocalizedMessage());
        }
    }

}
